<template>
  <div class="home">
    <h3>Welcome to Vue 3 Tech Demo</h3>
    <p>This is the home page.</p>
    <button @click="axiosSend">axios send</button>
    <textarea v-model="testText"></textarea>
    <button @click="handleRsaEncrypt">rsa encrypt</button>
    <button @click="handleRsaDecript">rsa decrypt</button>
    <hr />
    <textarea v-model="aesData"></textarea>
    <span>{{ aesKey }}</span>
    <button @click="handleAesEncrypt">aes encrypt</button>
    <hr />
    <textarea v-model="signDataStr"></textarea>
    <input type="text" v-model="signature" />
    <button @click="handleSignData">sha sign</button>
    <hr />
    rsa优化测试
    <textarea v-model="rsaEncryptContent"></textarea>
    <button @click="handleRsaDecryptBefore">原版rsa解密</button>
    <button @click="handleRsaDecrypt">优化rsa解密</button>
    <button @click="handleRsaDecryptWebWorker0">webWorker_rsa单线程解密</button>
    <button @click="handleRsaDecryptWebWorker">webWorker_rsa多线程解密</button>
    {{ rsaDecryptedContent }}
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import axiosInstance from '../api/index.js'
import forge from 'node-forge'
import { encryptConfig } from '../config/encrypt-config'

const counter = ref(0)

const rsaEncryptContent = ref('')
const rsaDecryptedContent = ref('')
const rsaPrivateKey = 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALceQpgtErsPJvYanZp12bI5rgPHeiX/neTGso3SEBZQJI2b3h/1CYmw1/DjayLqy8c4FQfdM+mJLHRTJ5tIFBQJlKSVT7sbohB82EZMCh5Q1BQPkML3vS1b5E1EQqSvZtl0FQLnEt0FRcG97bmDhfbOCdQ+PjxafxpUacqUQdIFAgMBAAECgYAQfga0avbRZyN0rd/87dlN/njoOTqMmpGPbb/eGwm84LnyERQ335tczdMdDHZ1Ph1dU3U9cJRA18xrq6OZDixUnJz6g95Pd4sJ/A203gtgNuzuhk1Zueu3OSpU1C9yJV7f6mfkBbayA+aglhWd7MciCskf+9UpE9Y+P6IJ4XDI7wJBAOPpTL7uoleZ+mtSkpjvMGhCzy0y1sHQm5JYU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wsOWnf4dmxgi/aIcBiHD5wPom+GA9wrHWtqa0C9og2wYHzYYCLvwt7q41qrZY39TOdgIH4RKJqpX6ciNt7BhmcPcVGuxAvOqhTws2KvcaEBHC/1fAtzQGGamYQSNqaactOBiFZqRMc9VvNLn/N/8jlVL6j7z3Qcl4CtfmDBuXwvFgDWNdwltItl57uYnm7eKUOFZEbqVy167rAe9mIF4402g4XdMFPGvraKN1GV2QfnJvWk3r+VjLILY9kpzdKqGwraBvQr3oS3ap5PtUH8pX1PKe2vR+jfRt8KCWidpsAF8u+a/6kv5IdOfi9rNeWWblCbSk/B9YndCLdOvd3M2gLKxiQyLdOKMJs8QG3c/FFPSKHlmQ8ckxK9FU/NR9OCpdVEPq1ba+zdgfLylaDMp6uxnO6H8z4ME9L+YFe4c98K5xDXs1cnuBk+8KyhsTpbFZ9fyPYu0AMroMTyxqiWFx/sFJFnSp6p+6iGUgJFMP0Tm63szCWG8FhG2M1OeBR6ddD2zYf8GOlRqMajyWVEMdVa7pA4weEdMXWmeh+AVa/sMwAprcfueqfI+dnEiqAnn6pEKLbTZ/7+36tQVueWGyFdJm2O97Lf9gv5II4V8oVXQFsBQkfrg2YU8nxqh6RlEmJyKZhfl2gome206i8YNX8JffBCbEUYhaKdju4aBgLyy6iWxyk78PNHSex0vu7otmhH85reeX4hLccCbHbRnP332tXEw8O19wpv8Ey1YxlHBSBIN04Q1f+PfmQaq31a1058gObQ9HEt/jhFuKvYY+gA7PdJrl8/DzKY5eAgO+4s4Y7V3T2bmhvtjmRINmDewisjosP3m+JMpzp4QHpR3W8QHaCax4AB9EogPSecdheEdXodpKEXx5g2LmZ6ehRLnuvYfcOY6w4FjFOlh0zml+VrnSLbAO3Efy2bjyZUjnD+fulIO2xxTbNogbXwsb1J4UCVjlh/5vHoU7Zb+WJzIHfbuE'

  if (!window.crypto || !crypto.subtle) {
    console.error('Web Crypto API 不支持，需降级处理');
  }

  // 加载3m大小的文本
  // @ts-ignore
  import('@/assets/encrypt-data/超长加密3m.txt?raw').then(module => {
    rsaEncryptContent.value = module.default
  })
})


const handleRsaDecryptBefore = () => {
  console.time('before')
  // 假设私钥存储在 encryptConfig.rsaServer.privateKey 中
  // 首先将私钥从 PEM 格式转换为 forge 中的私钥对象
  // const privateKeyPem = `-----BEGIN RSA PRIVATE KEY-----${encryptConfig.rsaServer.privateKey}-----END RSA PRIVATE KEY-----`;
  const privateKey = forge.pki.privateKeyFromPem(`-----BEGIN RSA PRIVATE KEY-----${rsaPrivateKey}-----END RSA PRIVATE KEY-----`);
  // 将 Base64 编码的加密数据解码为二进制数据
  const encryptedBinary = forge.util.decode64(rsaEncryptContent.value);
  // 计算每次解密的块大小
  const chunkSize = privateKey.n.bitLength() / 8;
  console.log("chunkSize", chunkSize);
  const encryptedBuffer = forge.util.createBuffer(encryptedBinary);
  const decryptedChunks: any[] = [];
  console.timeEnd('before')
  console.time('process')
  for (let i = 0; i < encryptedBinary.length; i += chunkSize) {
    const chunk = encryptedBuffer.getBytes(chunkSize);
    // 使用私钥进行解密操作
    // console.log("chunk", chunk);
    const decrypted = privateKey.decrypt(chunk, "RSA-OAEP", {
      md: forge.md.sha256.create(),
      mgf1: {
        md: forge.md.sha256.create(),
      },
    });
    // console.log("decrypted", decrypted);
    decryptedChunks.push(decrypted);
    // const decryptedBytes = forge.util.decodeUtf8(decrypted); // 二进制转UTF-8
    // decryptedChunks.push(decryptedBytes);
  }
  console.timeEnd('process')
  console.time('end')

  // 将解密后的块拼接为最终的明文数据
  const res = decryptedChunks.join("");


  const buffer = forge.util.createBuffer(res, "latin1" as any);
  const utf8String = buffer.toString();
  rsaDecryptedContent.value = utf8String;
  console.timeEnd('end')
}



async function importPrivateKey(pem) {
  const pemHeader = "-----BEGIN PRIVATE KEY-----";
  const pemFooter = "-----END PRIVATE KEY-----";
  // 去除 PEM 头尾和换行符
  const pemContents = pem.replace(pemHeader, '').replace(pemFooter, '').replace(/\s/g, '');
  // 转换为二进制 ArrayBuffer
  const binaryDer = Uint8Array.from(atob(pemContents), c => c.charCodeAt(0));

  return crypto.subtle.importKey(
    "pkcs8",          // 格式为 PKCS#8
    binaryDer,
    {
      name: "RSA-OAEP",
      hash: "SHA-256" // 与加密时算法一致[1,4](@ref)
    },
    true,             // 是否可导出
    ["decrypt"]       // 密钥用途
  );
}

async function handleRsaDecrypt() {
  console.log('start encrypt');
  console.time('total');
  // 导入私钥
  const privateKey = await importPrivateKey(`-----BEGIN PRIVATE KEY-----${rsaPrivateKey}-----END PRIVATE KEY-----`);
  console.log(privateKey)

  // Base64 转 ArrayBuffer
  const encryptedData = Uint8Array.from(atob(rsaEncryptContent.value), c => c.charCodeAt(0));

  // 分片处理（2048位密钥对应256字节块）
  const chunkSize = 128;
  const decryptedChunks: any[] = [];

  console.time('decrypt');
  for (let i = 0; i < encryptedData.length; i += chunkSize) {
    const chunk = encryptedData.slice(i, i + chunkSize);
    const decrypted = await crypto.subtle.decrypt(
      { name: "RSA-OAEP" },
      privateKey,
      chunk
    );
    decryptedChunks.push(new Uint8Array(decrypted));
  }
  console.timeEnd('decrypt');

  // 合并结果并转换为 UTF-8
  const merged = new Uint8Array(decryptedChunks.reduce((acc, arr) => acc + arr.length, 0));
  let offset = 0;
  decryptedChunks.forEach(arr => {
    merged.set(arr, offset);
    offset += arr.length;
  });

  rsaDecryptedContent.value = new TextDecoder().decode(merged);
  console.timeEnd('total');
}

// 创建 Worker 实例（Vite 特殊路径处理）
const worker = new Worker(new URL('../util/decrypt.worker0.js', import.meta.url));

// 单线程worker优化
async function handleRsaDecryptWebWorker0() {
  worker.onmessage = (e) => {
    if (e.data.error) {
      console.error('解密失败:', e.data.error);
    } else {
      rsaDecryptedContent.value = e.data.result;
    }
  };

  worker.onerror = (err) => {
    console.error('Worker 运行时错误:', err.message);
  };

  // 发送待解密数据
  worker.postMessage({
    privateKeyPem: `-----BEGIN PRIVATE KEY-----${rsaPrivateKey}-----END PRIVATE KEY-----`,
    encryptedBase64: rsaEncryptContent.value
  });
}

// 主线程预导入私钥并传递给Worker
let cachedCryptoKey:any = null;


// 主线程调用方法改造（使用多个Worker并行）
async function handleRsaDecryptWebWorker() {
  const workerCount = 2//navigator.hardwareConcurrency || 4; // 根据CPU核心数动态调整
  const chunkSize = 128; // 保持与Worker一致
  console.time('all worker')
  console.log('worker count:', workerCount)

  try {
    console.time('all begin')
    // 准备基础数据
    const encryptedData = Uint8Array.from(
      atob(rsaEncryptContent.value),
      c => c.charCodeAt(0)
    );

    if (!cachedCryptoKey) {
      const pem = `-----BEGIN PRIVATE KEY-----${rsaPrivateKey}-----END PRIVATE KEY-----`;
      cachedCryptoKey = await importPrivateKey(pem); // 复用之前的导入方法
    }

    // 分片处理
    const chunks: any = [];
    for (let i = 0; i < encryptedData.length; i += chunkSize) {
      chunks.push(encryptedData.slice(i, i + chunkSize));
    }

    // 任务分配（平均分配分片到不同Worker）
    const workers: any[] = [];
    const chunksPerWorker = Math.ceil(chunks.length / workerCount);

    console.timeEnd('all begin')

    for (let i = 0; i < workerCount; i++) {
      const startIdx = i * chunksPerWorker;
      const endIdx = startIdx + chunksPerWorker;
      workers.push(
        createWorkerTask(
          chunks.slice(startIdx, endIdx),
          // rsaPrivateKey,
          cachedCryptoKey
        )
      );
    }

    // 并行执行 & 合并结果
    console.time('all process')
    const results = await Promise.all(workers);
    const merged = mergeResults(results);
    rsaDecryptedContent.value = new TextDecoder().decode(merged);

    console.timeEnd('all process')
    console.timeEnd('all worker')

  } catch (err) {
    console.error('解密失败:', err);
  }
}

// 创建Worker任务
function createWorkerTask(chunks, cachedCryptoKey) {
  return new Promise((resolve, reject) => {
    // const worker = new Worker('./rsaDecrypt.worker.js', { type: 'module' });
    const worker = new Worker(new URL('../util/decrypt.worker.js', import.meta.url));

    // 转换分片为可传输格式
    // const transferableChunks = chunks.map(chunk => {
    //   const str = btoa(String.fromCharCode(...chunk));
    //   return str;
    // });

    worker.postMessage({
      // privateKeyPem: `-----BEGIN PRIVATE KEY-----${privateKey}-----END PRIVATE KEY-----`,
      cryptoKey: cachedCryptoKey, // 关键修改：传递已导入的CryptoKey
      chunks //transferableChunks
    });

    worker.onmessage = (e) => {
      if (e.data.error) {
        worker.terminate();
        reject(e.data.error);
      } else {
        worker.terminate();
        resolve(new Uint8Array(e.data.result));
      }
    };

    worker.onerror = (err) => {
      worker.terminate();
      reject(err.message);
    };
  });
}

// 合并结果的优化方法
function mergeResults(results) {
  const totalLength = results.reduce((sum, arr) => sum + arr.length, 0);
  const merged = new Uint8Array(totalLength);
  let offset = 0;

  for (const arr of results) {
    merged.set(arr, offset);
    offset += arr.length;
  }
  return merged;
}


function incrementCounter() {
  counter.value++;
}

async function axiosSend() {
  try {
    const response = await axiosInstance.get('/onlinedocapi/hello/doc/world');
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
}

/****************** rsa加密解密 **********************/

function calcPublicKey() {
  const publicKeyPem = `-----BEGIN PUBLIC KEY-----${encryptConfig.rsaClient.publicKey}-----END PUBLIC KEY-----`
  const publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
  return publicKey;
}


function calcPrivateKey() {
  const privateKeyPem = `-----BEGIN RSA PRIVATE KEY-----${encryptConfig.rsaClient.privateKey}-----END RSA PRIVATE KEY-----`
  const privateKey = forge.pki.privateKeyFromPem(privateKeyPem)
  return privateKey
}

function rsaEncrypt(data) {
  const publicKey = calcPublicKey()
  const buffer = forge.util.createBuffer(data, 'utf8');
  const encrypted = publicKey.encrypt(buffer.getBytes(), 'RSAES-PKCS1-V1_5');
  return forge.util.encode64(encrypted);
}

function rsaDecrypt(data) {
  const privateKey = calcPrivateKey()
  const decrypted = privateKey.decrypt(forge.util.decode64(data), 'RSAES-PKCS1-V1_5');
  console.log('decrypt:', decrypted);
  // 注：latin1可能是前端默认的编码方式，如果改为utf8反而显示不出来
  const buffer = forge.util.createBuffer(decrypted, 'latin1' as any);

  const utf8String = buffer.toString()
  console.log('utf8:', utf8String)
  return utf8String;
  // return decrypted;
}

// 加密函数
// 分段这里特别需要注意：以byte数组形式作为参数分段，同样以bytes数组形式作为分段结果。而创建buffer也好，base64化也好，统统放在最后进行
function encryptRSAESPKCS1V1_5(data: string) {
  // const publicKeyPem=encryptConfig.rsaServer.publicKey
  // const publicKeyPem=`-----BEGIN PUBLIC KEY-----${encryptConfig.rsaServer.publicKey}-----END PUBLIC KEY-----`
  // const publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
  const publicKey = calcPublicKey()
  const chunkSize = publicKey.n.bitLength() / 8 - 11;
  const buffer = forge.util.createBuffer(data, 'utf8')
  let encryptedChunks: string[] = [];
  for (let i = 0; i < data.length; i += chunkSize) {
    let chunk = buffer.getBytes(Math.min(chunkSize, buffer.length() - i))
    let encrypted = publicKey.encrypt(chunk, 'RSAES-PKCS1-V1_5');
    encryptedChunks.push(encrypted);
  }
  const res = forge.util.encode64(encryptedChunks.join(''))
  return res;
}

function decryptRSAESPKCS1V1_5(encryptedData) {
  // 假设私钥存储在 encryptConfig.rsaServer.privateKey 中
  // 首先将私钥从 PEM 格式转换为 forge 中的私钥对象
  // const privateKeyPem = `-----BEGIN RSA PRIVATE KEY-----${encryptConfig.rsaServer.privateKey}-----END RSA PRIVATE KEY-----`;
  // const privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
  const privateKey = calcPrivateKey();
  // 将 Base64 编码的加密数据解码为二进制数据
  const encryptedBinary = forge.util.decode64(encryptedData);
  // 计算每次解密的块大小
  const chunkSize = privateKey.n.bitLength() / 8;
  let encryptedBuffer = forge.util.createBuffer(encryptedBinary);
  let decryptedChunks: string[] = [];
  for (let i = 0; i < encryptedBinary.length; i += chunkSize) {
    console.log('chunk:', i)
    let chunk = encryptedBuffer.getBytes(chunkSize);
    // 使用私钥进行解密操作
    let decrypted = privateKey.decrypt(chunk, 'RSAES-PKCS1-V1_5');
    decryptedChunks.push(decrypted);
  }
  // 将解密后的块拼接为最终的明文数据
  const res = decryptedChunks.join('');

  const buffer = forge.util.createBuffer(res, 'latin1' as any);

  const utf8String = buffer.toString()

  return utf8String;
}

const testText = ref('你好123')

function handleRsaEncrypt() {
  const data = testText.value
  console.log('org data:', data);
  const res = rsaEncrypt(data)
  console.log(res);
}

function handleRsaDecript() {
  const data = testText.value
  const res = decryptRSAESPKCS1V1_5(data)
  console.log(res)

}

/********************* aes加密解密测试 *************************/

const aesData = ref('这时aes的原始数据')
const aesKey = ref('')

// 生成 128 位密钥
function generateKey() {
  const key = forge.random.getBytesSync(16); // 128 位密钥
  return key;
}

// 加密函数
function encryptDataECB(data, key) {
  const cipher = forge.cipher.createCipher('AES-ECB', key);
  cipher.start();
  cipher.update(forge.util.createBuffer(data));
  cipher.finish();
  const encrypted = cipher.output;
  return forge.util.encode64(encrypted.getBytes());
}

// 解密函数
function decryptDataECB(encryptedData, key) {
  const encryptedBytes = forge.util.decode64(encryptedData);
  const decipher = forge.cipher.createDecipher('AES-ECB', key);
  decipher.start();
  decipher.update(forge.util.createBuffer(encryptedBytes));
  decipher.finish();
  return decipher.output.toString();
}

function handleAesEncrypt() {
  const aesKeyBytes = generateKey()
  aesKey.value = forge.util.encode64(aesKeyBytes)
  const buffer = forge.util.createBuffer(aesData.value, 'utf8')
  const res = encryptDataECB(buffer, aesKeyBytes)
  console.log('aes req:', res)
}


/*********************** sha256withRsa签名 ******************************/

const signDataStr = ref('')
const signature = ref('')

function calcShaPrivateKey() {
  const privateKeyPem = `-----BEGIN RSA PRIVATE KEY-----${encryptConfig.shaClient.privateKey}-----END RSA PRIVATE KEY-----`
  const privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
  return privateKey;
}

function calcShaPublicKey() {
  const publicKeyPem = `-----BEGIN PUBLIC KEY-----${encryptConfig.shaServer.publicKey}-----END PUBLIC KEY-----`
  const publicKey = forge.pki.publicKeyFromPem(publicKeyPem)
  return publicKey
}

function signData(data) {
  const privateKey = calcShaPrivateKey()
  const md = forge.md.sha256.create();
  md.update(data, 'utf8');
  const signature = privateKey.sign(md);
  return forge.util.encode64(signature);
}

function verifySignature(data, signature) {
  const publicKey = calcPublicKey()
  const md = forge.md.sha256.create();
  md.update(data, 'utf8');
  const decodedSignature = forge.util.decode64(signature);
  return publicKey.verify(md.digest().bytes(), decodedSignature);
}

function handleSignData() {
  const signatureRes = signData(signDataStr.value)
  console.log('before sign:', signDataStr.value);
  signature.value = signatureRes
  console.log('signature:', signatureRes)
}


</script>

<style scoped>
.home {
  text-align: left;
  margin-top: 50px;
  display: flex;
  flex-direction: column;
}

button {
  margin-top: 20px;
  padding: 10px 20px;
  font-size: 16px;
}
</style>